package com.example.flower_shop.websocket;

import cn.dev33.satoken.stp.StpUtil;
import com.example.flower_shop.enums.RoleEnum;
import com.example.flower_shop.service.usr.AuthService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class WebSocketInterceptor implements HandshakeInterceptor {
    @Resource
    private AuthService authService;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        String pToken = request.getURI().getQuery().split("=")[1];
        if (StringUtils.isBlank(token) && StringUtils.isBlank(pToken)) {
            return false;
        }
        Object userId = StpUtil.getLoginIdByToken(pToken);
        if (userId == null) {
            return false;
        }
        List<String> roles = authService.getRolesByUserId(userId);
        if (roles == null || roles.isEmpty()) {
            return false;
        }
        if (roles.contains(RoleEnum.ADMIN.getRole())) {
            attributes.put("isAdmin", true);
        } else {
            attributes.put("isAdmin", false);
        }
        attributes.put("userId", userId);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {

    }
}
